<!DOCTYPE html>
<html>
    <head>
        <title>Markdown Editor</title>
        <script src="../script/jquery.min.js"></script>
        <script src="../script/ao_module.js"></script>
        <link rel="stylesheet" href="script/SimpleMDE/simplemde.min.css">
        <script src="script/SimpleMDE/simplemde.min.js"></script>
        <style>
            html, body{
                background-color:white;
                height: calc(100% - 80px);
            }
            #maintext{
                height:100% !important;
            }
        </style>
    </head>
    <body> 
        <textarea id="maintext"></textarea>
        <script>
            var simplemde;          //SimpleMDE editor object
            var filepath = "";      //Current editing filepath
            var files = ao_module_loadInputFiles();
            var originalTitle = "MDEditor";
            var lastSaveContent = ""; //Content for last saved content
            
            $(window).on("keydown",function(event) {
                if (event.which == 83 && event.ctrlKey){
                    event.preventDefault();
                    saveText();
                }else if (event.target.tagName == "TEXTAREA"){
                    //Some wierd hack to make SimpleMDE to work with ArozOS IME API
                    if (parent.window.ime){
                        parent.window.ime.focus = event.target;
                        if (parent.window.ime.handler != null){
                            parent.window.ime.handler(event);
                        }
                    }
                    
                }
            });

            if (files !== null && files.length > 0){
                //Set the window name
                ao_module_setWindowTitle("MDEditor - " + files[0].filename);
                originalTitle = "MDEditor - " + files[0].filename;
                //Check if there are more than 1 text files to be opened. If yes, open new windows.
                if (files.length > 1){
                    for (var i = 1; i < files.length; i++){
                        var thisFilelist = [{
                            filename: files[i].filename,
                            filepath: files[i].filepath
                        }];
                        thisFilelist = encodeURIComponent(JSON.stringify(thisFilelist));
                        ao_module_newfw({
                            url: "MDEditor/mde.html#" + thisFilelist,
                            width: 1080,
                            height: 580,
                            appicon: "MDEditor/img/notebook.png",
                            title: "MDEditor",
                        });
                    }
                }
               
                filepath = files[0].filepath;

                //Check if this is json. If yes, parse it to string before displaying to prevent the [object Object] bug
                var ext = filepath.split(".").pop();
                var isJson = false;
                if (ext == "json"){
                    isJson = true;
                }

                //Load the file into the textarea
                $.get("../../media?file=" + files[0].filepath + "#" + Date.now(),function(data){
                    if (isJson){
                        data = JSON.stringify(data);
                    }
                    $("#maintext").text(data);
                    lastSaveContent = data;
                    //Load Markdown Editor
                    simplemde = new SimpleMDE({
                        autofocus: true,
                        element: document.getElementById("maintext"),
                        forceSync: true,
                        insertTexts: {
                            horizontalRule: ["", "\n\n-----\n\n"],
                            image: ["![](http://", ")"],
                            link: ["[", "](http://)"],
                            table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
                        },
                        placeholder: "(Empty file)",
                        //promptURLs: true,
                        renderingConfig: {
                            singleLineBreaks: true,
                            codeSyntaxHighlighting: true,
                        },
                        toolbar: ["bold","italic","heading","|","code","quote","unordered-list","ordered-list","|","link","image","table","|","preview","side-by-side","fullscreen","|",
                        {
                            name: "savebtn",
                            action: function(){
                                saveText();
                            },
                            className: "fa fa-floppy-o",
                            title: "Save",
                        },"guide","|"],
                        spellChecker: false,
                        status: ["autosave", "lines", "words", "cursor"], // Optional usage
                    });
                });
            }else{
                simplemde = new SimpleMDE({ element: document.getElementById("maintext") });
            }

            function handleNewFileSave(filedata){
                for (var i=0; i < filedata.length; i++){
                    var thisFilename = filedata[i].filename;
                    var thisFilepath = filedata[i].filepath;
                    
                    //Update the current editing filepath
                    filepath = thisFilepath;

                    ao_module_setWindowTitle("MDEditor - " + thisFilename);
                    originalTitle = "MDEditor - " + thisFilename;
                }

                saveText();
            }
          
            function saveText(callback=undefined){
                if (filepath == ""){
                    //This is a new file. Ask for save directory.
                    ao_module_openFileSelector(handleNewFileSave, "user:/Desktop", "new",false, {
                        defaultName: "Untitled.md"
                    });
                    return;
                }
                var newcontent = simplemde.value();
                ao_module_agirun("./MDEditor/filesaver.js", {
                    filepath: filepath, 
                    content: newcontent
                }, function(data){
                    console.log(data);
                    if (data.error !== undefined){
                        alert(data.error);
                    }else{
                        //Save succeed. Update last saved content
                        lastSaveContent = newcontent;

                        //Update the title as well
                        ao_module_setWindowTitle(originalTitle);

                        if (callback != undefined){
                            callback();
                        }
                    }
                }, function(){
                    alert("Save File Failed!")
                });

            }


            setInterval(function(){
                //Check if the content from last save matched the current value on simplemde 
                if (!isSaved()){
                    ao_module_setWindowTitle(originalTitle + " *");
                }else{
                    //No new changes
                    ao_module_setWindowTitle(originalTitle);
                }

            }, 1000);

            function isSaved(){
                var currentContent = simplemde.value();
                return (lastSaveContent == currentContent);
            }

            //Overwrite the ao_module_close function to allow 
            if (!ao_module_virtualDesktop){
                window.onbeforeunload = function(){
                    if (!isSaved()){
                        return "Content is not saved. Confirm Exit?";
                    }
                }
            }

            //Overwrite the close sequence
            function ao_module_close(){
                if (!isSaved()){
                    //Not saved
                    if (confirm("Some changes are not saved. Save before exit?")){
                        saveText(function(){
                            //Exit after save
                            closeThisWindow();
                        });
                    }else{
                        //User request not to save
                        closeThisWindow();
                    }
                }else{
                    //Saved. Exit
                    closeThisWindow();
                }
            }

            function closeThisWindow(){
                ao_module_closeHandler();
            }
       </script>
    </body>
</html>